package com.yx.cloud.map.layer;

import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;

import com.aaa.lib.map.MapUtils;
import com.aaa.lib.map.MapView;
import com.yx.cloud.R;
import com.iot.common.utils.LogUtils;

public class YXSweeperLayer extends YXImageMarkerLayer {

    private Matrix matrix;
    private float scale = 1;
    private Paint paint;
    private float scaleRadiu;
    private PointF tmpPoint;
    private float lastx = -1;
    private float lasty = -1;

    public YXSweeperLayer(MapView mapView) {
        super(mapView);
        markerBitmap = BitmapFactory.decodeResource(mResource, R.mipmap.robot_inmap);
        iconRadiu = markerBitmap.getWidth() / 2;
        scaleRadiu = iconRadiu;
        matrix = new Matrix();
        paint = new Paint();
        paint.setColor(mResource.getColor(R.color.shadow_aa));
        tmpPoint = new PointF();
    }

    /**
     * 不设置角度的情况下 根据上次的位置计算当前朝向
     */
    public void setMarker(float x, float y) {
        if (markerPosition.x == 0 && markerPosition.y == 0) {
            setMarker(x, y, 0);
        } else {
            //新的图标位置和现在一样 直接不更新  否则 计算出来的方向时0度
            if (lastx == x && lasty == y) {
                return;
            }

            double radiu = Math.atan2((y - markerPosition.y), (x - markerPosition.x)); //弧度
            double angle = radiu * (180 / Math.PI); //角度
            setMarker(x, y, (float) angle + 90); //这里加的90度是因为图片本身是朝上的 也就是-90度  所以要转向0度

            lastx = x;
            lasty = y;
        }
    }
    public void setMarker(float x, float y,float rotation) {
            super.setMarker(x, y, rotation+90);//这里加的90度是因为图片本身是朝上的 也就是-90度  所以要转向0度

    }

    @Override
    public void draw(Canvas canvas) {
        if (!visible) {
            return;
        }
        if (markerBitmap == null || markerBitmap.isRecycled()) {
            return;
        }
        if (markerPosition == null || (markerPosition.x == 0 && markerPosition.y == 0)) {
            return;
        }

        LogUtils.i("YXImageMarkerLayer  x : " + markerPosition.x + " y : " + markerPosition.y);

        //TODO 其实也应该用矩阵变换来实现 到图片中心点的偏移
        //        scaleRadiu=(scaleRadiu+0.2f)>iconRadiu*1.2f?iconRadiu*2/3:(scaleRadiu+0.2f);

        MapUtils.getTransformedPoint(mMapView.getTransform(), markerPosition.x, markerPosition.y, tmpPoint);

        //绘制图标 设置位置和偏移
        matrix.setTranslate(tmpPoint.x - iconRadiu, tmpPoint.y - iconRadiu);
        matrix.postRotate(rotation, tmpPoint.x, tmpPoint.y);
        canvas.drawBitmap(markerBitmap, matrix, null);
    }
}
